//
//  SAOCRViewController.m
//  saasRetail
//
//  Created by mac on 2022/11/26.
//

#import "SAOCRViewController.h"
#import <HSFaceDetector/LiveHeader.h>
#import <HSFaceDetector/LiveDetectController.h>
#import <HSFaceDetector/LiveCamera.h>
#import "UIView+Toast.h"
#import "SettingViewController.h"
#import "ResultViewController.h"
#import "MBProgressHUD.h"
#import "AppDeviceUtils.h"

#define LIVE_IP @"http://lic.biometric.net.cn:11080"
#define SERVICE_LIVE @"ivsign-bio-rs/facehbie/picyunEncrypt"
#define TBBOUNDARY @"golang"
#define UNKNOWN_CODE 99999

@interface SAOCRViewController ()<LiveDetectControllerDelegate, NSURLSessionDelegate>
@property (nonatomic, copy)NSString *liveIP;
@end

@implementation SAOCRViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self initView];
    
    NSString *expireDate = [LiveCamera getExpireDate:[FaceDataBundle pathForResource:@"Mobile_Live.lic" ofType:nil inDirectory:@"lic"]];
    NSLog(@"expireDate = %@",expireDate);
//    [self.view makeToast:[NSString stringWithFormat:@"授权有效期至 : %@", expireDate]];
    
    [self startLive];

}


- (void)startLive{
    [self beginDetect:NO];
}

- (void)beginDetect:(BOOL)isCameraBack{
    NSString *ipString = [[NSUserDefaults standardUserDefaults]objectForKey:@"live_ip"];
    if (ipString == nil || ipString.length == 0) {
        self.liveIP = LIVE_IP;
    }else {
        self.liveIP = ipString;
    }
    if (![self.liveIP hasPrefix:@"https://"] && ![self.liveIP hasPrefix:@"http://"]) {
        [self.view makeToast:@"请配置正确的 IP 地址, 以 http:// 或 https:// 开头"];
        return;
    }

    NSInteger liveMode = [[NSUserDefaults standardUserDefaults]integerForKey:@"live_mode"];
    
    LiveDetectController *liveVc = [[LiveDetectController alloc]init];
    if (liveMode == 0) {
        NSMutableArray *temp = [self randomArray:@[@2, @3, @4, @5] withRandomNum:2];
        [temp addObject:@1];
        liveVc.actionList = [temp copy];
    }else{
        liveVc.actionList = @[@1];
    }
    liveVc.minFaceSize = [[[NSUserDefaults standardUserDefaults]objectForKey:@"min_face_size"] intValue];
    liveVc.maxFaceSize = [[[NSUserDefaults standardUserDefaults]objectForKey:@"max_face_size"] intValue];
    liveVc.actionTimeout = [[[NSUserDefaults standardUserDefaults]objectForKey:@"time_out_second"] intValue];
    liveVc.delegate = self;
    liveVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:liveVc animated:YES completion:nil];
    
}

#pragma mark -
#pragma mark LiveDetectControllerDelegate

- (void)onFailed:(int)code withMessage:(NSString *)message{
    if (code != IV_ERROR_BREAK) {
        ResultViewController *resultVc = [[ResultViewController alloc]init];
        resultVc.errorCode = code;
        resultVc.errorMessage = message;
        [self.navigationController pushViewController:resultVc animated:YES];
    }else{
        [self.view makeToast:message];
    }
}

- (void)onFinishWithSign:(NSString *)imageSign{
    [self checkLiveService:imageSign];
}

- (void)initView{
    self.view.backgroundColor = HSBlueColor;
    NSString *imageFolder = [FaceDataBundle pathForResource:@"image" ofType:nil];
    
    UIImageView *mainView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREENWIDTH/6, 44+NavBarPadding, SCREENWIDTH/3*2, SCREENWIDTH/3*2)];
    mainView.image = [UIImage imageNamed:[imageFolder stringByAppendingPathComponent:@"main.png"]];
    mainView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(settingView)];
    tap.numberOfTapsRequired = 2;
    [mainView addGestureRecognizer:tap];
    [self.view addSubview:mainView];
    
    UIImageView *titleView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREENWIDTH/8, CGRectGetMaxY(mainView.frame), SCREENWIDTH/4*3, SCREENWIDTH/6)];
    titleView.image = [UIImage imageNamed:[imageFolder stringByAppendingPathComponent:@"title2.png"]];
    [self.view addSubview:titleView];
    
    CGFloat viewW = SCREENWIDTH/8;
    CGFloat viewH = viewW;
    CGFloat marginX = (SCREENWIDTH - viewW * 4)/5;
    CGFloat marginY = CGRectGetMaxY(titleView.frame)+marginX;
    CGFloat labW = viewW + marginX * 2;
    CGFloat labH = labW/5;
    UIImageView *gazeView = [[UIImageView alloc]initWithFrame:CGRectMake(marginX, marginY, viewW, viewH)];
    gazeView.image = [UIImage imageNamed:[imageFolder stringByAppendingPathComponent:@"gazy.png"]];
    [self.view addSubview:gazeView];
    UILabel *gazeLab = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(gazeView.frame), labW, labH)];
    gazeLab.textColor = HSGreenColor;
    gazeLab.text = @"正对手机";
    gazeLab.font = [UIFont systemFontOfSize:14];
    gazeLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:gazeLab];
    
    UIImageView *keepView = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(gazeView.frame) + marginX, marginY, viewW, viewH)];
    keepView.image = [UIImage imageNamed:[imageFolder stringByAppendingPathComponent:@"keep.png"]];
    [self.view addSubview:keepView];
    UILabel *keepLab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(gazeView.frame), CGRectGetMaxY(keepView.frame), labW, labH)];
    keepLab.textColor = HSGreenColor;
    keepLab.text = @"稳定姿态";
    keepLab.font = [UIFont systemFontOfSize:14];
    keepLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:keepLab];
    
    UIImageView *maskView = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(keepView.frame) + marginX, marginY, viewW, viewH)];
    maskView.image = [UIImage imageNamed:[imageFolder stringByAppendingPathComponent:@"mask.png"]];
    [self.view addSubview:maskView];
    UILabel *maskLab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(keepView.frame), CGRectGetMaxY(maskView.frame), labW, labH)];
    maskLab.textColor = HSGreenColor;
    maskLab.text = @"摘掉口罩";
    maskLab.font = [UIFont systemFontOfSize:14];
    maskLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:maskLab];
    
    UIImageView *lightView = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(maskView.frame) + marginX, marginY, viewW, viewH)];
    lightView.image = [UIImage imageNamed:[imageFolder stringByAppendingPathComponent:@"light.png"]];
    [self.view addSubview:lightView];
    UILabel *lightLab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(maskView.frame), CGRectGetMaxY(lightView.frame), labW, labH)];
    lightLab.textColor = HSGreenColor;
    lightLab.text = @"光线充足";
    lightLab.font = [UIFont systemFontOfSize:14];
    lightLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:lightLab];
    
    UIButton *beginBtn = [[UIButton alloc]initWithFrame:CGRectMake(marginX, SCREENHEIGHT - 128 - HomeBarPadding, SCREENWIDTH - marginX * 2, 44)];
    beginBtn.layer.masksToBounds = YES;
    beginBtn.layer.cornerRadius = beginBtn.frame.size.height / 10;
    beginBtn.backgroundColor = HSGreenColor;
    [beginBtn setTitle:@"开启活体检测" forState:UIControlStateNormal];
    [beginBtn setTitleColor:HSBlueColor forState:UIControlStateNormal];
    [beginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [beginBtn addTarget:self action:@selector(startLive) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:beginBtn];
    
    UILabel *versionLab = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(beginBtn.frame) + 20, SCREENWIDTH, 44)];
    versionLab.textColor = HSGreenColor;
    versionLab.font = [UIFont systemFontOfSize:16];
    versionLab.textAlignment = NSTextAlignmentCenter;
    NSString *sdkVersion = LiveCamera.getVersion;
    versionLab.text = [NSString stringWithFormat:@"Version: %@",sdkVersion];
    [self.view addSubview:versionLab];
    
}

- (void)settingView{
    SettingViewController *svc = [[SettingViewController alloc]init];
    [self.navigationController pushViewController:svc animated:YES];
}

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    }
}

- (void)checkLiveService:(NSString *)signImage{

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
           
    NSString *liveUrl = [self.liveIP stringByAppendingPathComponent:SERVICE_LIVE];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:liveUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0f];
    [request setHTTPMethod:@"POST"];

    [request addValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",TBBOUNDARY] forHTTPHeaderField:@"Content-Type"];
    NSMutableString *content = [NSMutableString stringWithFormat:@"--%@\r\n", TBBOUNDARY];
    [content appendString:@"Content-Disposition: form-data; name=\"name\"\r\n\r\n"];
    [content appendString:[AppDeviceUtils getDeviceModel]];
    [content appendString:[NSString stringWithFormat:@"\r\n--%@\r\n", TBBOUNDARY]];
    [content appendString:@"Content-Disposition: form-data; name=\"companyName\"\r\n\r\n"];
    [content appendString:@"hisign"];
    [content appendString:[NSString stringWithFormat:@"\r\n--%@\r\n", TBBOUNDARY]];
    [content appendString:@"Content-Disposition: form-data; name=\"image\"\r\n\r\n"];
    [content appendString:[NSString stringWithFormat:@"HS%@", signImage]];
    [content appendString:[NSString stringWithFormat:@"\r\n--%@--\r\n", TBBOUNDARY]];
    [request setHTTPBody:[content dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLSession *session = nil;
    if ([self.liveIP hasPrefix:@"https"]) {
        session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    }else {
        session = [NSURLSession sharedSession];
    }
    [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
        if (error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self serveToFail:error.domain];
            });
        }else{
            NSError *jsonError;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
            if (dict == nil || jsonError) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self serveToFail:@"JSON解析异常"];
                });
            }else{
                if ([[dict objectForKey:@"status"]isKindOfClass:[NSString class]]) {
                    NSString *status = [dict objectForKey:@"status"];
                    NSString *msg = [dict objectForKey:@"message"];
                    if ([status isEqualToString:@"0"]) {
                        NSString *captureStatus = [dict objectForKey:@"captureStatus"];
                        UIImage *showImage = nil;
                        if ([captureStatus isEqualToString:@"GOOD"]) {
                            NSString *returnPic = [dict objectForKey:@"returnpic"];
                            if (returnPic != nil) {
                                NSData *picData = [[NSData alloc]initWithBase64EncodedString:returnPic options:0];
                                showImage = [UIImage imageWithData:picData];
                            }
                        }
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self toSuccess:captureStatus showImage:showImage];
                        });
                    }else {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self serveToFail:msg];
                        });
                    }
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self serveToFail:@"服务端访问异常"];
                    });
                }
                
            }
        }
    }]resume];
}

- (void)serveToFail:(NSString *)message{
    NSLog(@"server live faid = %@", message);
    ResultViewController *resultVc = [[ResultViewController alloc]init];
    resultVc.errorCode = UNKNOWN_CODE;
    resultVc.errorMessage = message;
    [self.navigationController pushViewController:resultVc animated:YES];
   
}

- (void)toSuccess:(NSString *)status showImage:(UIImage *)liveImage{
    NSLog(@"server live staus = %@", status);
    int liveCode = UNKNOWN_CODE;
    if ([status isEqualToString:@"GOOD"]) {
        liveCode = IV_ERROR_NONE;
    }else if ([status isEqualToString:@"NON_LIVE"]) {
        liveCode = IV_ERROR_NOTLIVE;
    }
    ResultViewController *resultVc = [[ResultViewController alloc]init];
    resultVc.errorCode = liveCode;
    resultVc.errorMessage = [self parseCaptureStatus:status];
    resultVc.liveImage = liveImage;
    [self.navigationController pushViewController:resultVc animated:YES];
    
}

- (NSString *)parseCaptureStatus:(NSString *)status{
    if ([status isEqualToString:@"NONE"]) {
        return @"无人脸";
    }else if ([status isEqualToString:@"GOOD"]) {
        return @"活体";
    }else if ([status isEqualToString:@"NON_LIVE"]) {
        return @"非活体";
    }else if ([status isEqualToString:@"NEAR"]) {
        return @"人脸过近";
    }else if ([status isEqualToString:@"FAR"]) {
        return @"人脸过远";
    }else if ([status isEqualToString:@"TILTED"]) {
        return @"人脸姿态不正";
    }else if ([status isEqualToString:@"SIDE"]) {
        return @"人脸位置靠近边缘";
    }else if ([status isEqualToString:@"MOVING"]) {
        return @"人脸运动模糊";
    }else if ([status isEqualToString:@"NO_MOUTH"]) {
        return @"嘴巴遮挡";
    }else if ([status isEqualToString:@"NO_EYE"]) {
        return @"眼睛遮挡";
    }else if ([status isEqualToString:@"NO_NOSE"]) {
        return @"鼻子遮挡";
    }else {
        return status;
    }
}

//随机数组
- (NSMutableArray *)randomArray:(NSArray *)array withRandomNum:(NSInteger)num {
    
    NSMutableArray *startArray = [[NSMutableArray alloc] initWithArray:array];
    //随机数产生结果
    NSMutableArray *resultArray = [[NSMutableArray alloc] initWithCapacity:0];
    //随机数个数
    for (int i = 0; i < num; i++) {
        int t = arc4random() % startArray.count;
        resultArray[i] = startArray[t];
        startArray[t] = [startArray lastObject]; //为更好的乱序，故交换下位置
        [startArray removeLastObject];
    }
    return resultArray;
}

@end

